package com.asset.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.asset.common.BaseResponse;
import com.asset.common.ErrorCode;
import com.asset.common.ResultUtils;
import com.asset.exception.BusinessException;
import com.asset.exception.ThrowUtils;
import com.asset.model.dto.user.UserLoginRequest;
import com.asset.model.entity.User;
import com.asset.model.vo.LoginUserVO;
import com.asset.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户登录, 普通 Cookie Session 写法
     *
     * @param userLoginRequest
     * @return
     */
//    @PostMapping("/login")
//    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
//        System.out.println("Intercepting path: " + request.getRequestURI());
//        // 判断请求是否为空
//        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
//        String username = userLoginRequest.getUsername();
//        String password = userLoginRequest.getPassword();
//        LoginUserVO loginUserVo = userService.userLogin(username, password, request);
//        System.out.println(loginUserVo);
//        return ResultUtils.success(loginUserVo);
//    }

    /**
     * 使用 sa-token 登录
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest) {
        // 获取用户名
        String username = userLoginRequest.getUsername();
        // 获取密码
        String password = userLoginRequest.getPassword();
        // 获取用户
        LoginUserVO userVO = userService.userLogin(username, password);
        // 获取用户id
        Integer userId = userVO.getId();
        if (userId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        return ResultUtils.success(userVO);
    }

    /**
     * 获取当前登录用户
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser() {
        LoginUserVO loginUser = userService.getLoginUserVOByTK();
        return ResultUtils.success(loginUser);
    }

    /**
     * 用户注销
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout() {
        // 使用 sa-token 获取 request, 写法
        ThrowUtils.throwIf(!StpUtil.isLogin(), ErrorCode.OPERATION_ERROR, "当前没有用户登录");
        boolean result = userService.userLogout();
        return ResultUtils.success(result);
    }
}
